package com.yylending.las.lending;

import android.Manifest;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.common.lockpattern.Constant;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Constants;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.location.LocationPresenter;
import com.yylending.las.common.location.entity.Location;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.common.widgets.RedDotView;
import com.yylending.las.common.widgets.TelephoneTextView;
import com.yylending.las.lending.outlet.OutletActivity;
import com.yylending.las.lending.process.PreIncreaseLimitActivity;
import com.yylending.las.lending.process.ProcessActivity;
import com.yylending.las.lending.process.confirmloan.ConfirmLoanModel;
import com.yylending.las.lending.process.confirmloan.ConfirmLoanPresenter;
import com.yylending.las.lending.quota.baseinfo.CustomerInfoPresenter;
import com.yylending.las.lending.quota.entity.CustomerBean;
import com.yylending.las.lending.quota.idcard.IdCardModel;
import com.yylending.las.lending.quota.myquota.MyQuotaModel;
import com.yylending.las.lending.quota.myquota.MyQuotaPresenter;
import com.yylending.las.main.MainController;
import com.yylending.las.personal.bandcard.BankCardActivity;
import com.yylending.las.personal.bandcard.BankCardModel;
import com.yylending.las.personal.bandcard.BankCardPresenter;
import com.yylending.las.personal.bandcard.BoundBankCards;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 额度与借款审批之后的状态综合显示页
 * Created by laixj on 2017/11/7.
 * Copyright ©2016 www.yylending.com. All Rights Reserved.
 */
public class ComplexStatusFragment extends BaseFragment implements View.OnClickListener,
		BankCardPresenter.View, ConfirmLoanPresenter.View, LocationPresenter.View, CustomerInfoPresenter.View {
	static final String ARG_APPLY_STATUS = "arg_apply_status";
	static final String ARG_SAVED_TAB = "arg_saved_tab";

	private static final int LOADER_ID_BANK = 2;
	private static final int LOADER_ID_CONFIRM_LOAN = 3;
	private static final int LOADER_ID_LOCATE = 4;
	private static final int LOADER_ID_CUSTOMER_INFO = 5;
	/**
	 * 手机借钱页
	 */
	private static final int PAGE_ONLINE = 0;
	/**
	 * 门店借钱页
	 */
	private static final int PAGE_OUTLET = 1;

	Unbinder unbinder;
	@BindView(R.id.title_left_iv)
	ImageView mTitleLeftIv;
	@BindView(R.id.title_tv)
	TextView mTitleTv;
	@BindView(R.id.title_right_tv)
	TextView mTitleRightTv;
	@BindView(R.id.title_right_iv)
	ImageView mTitleRightIv;
	@BindView(R.id.layout_title_bar)
	RelativeLayout mLayoutTitleBar;
	@BindView(R.id.red_dot_view)
	RedDotView mRedDotView;
	@BindView(R.id.high_quota_direct_tab_online)
	TextView mTabOnline;
	@BindView(R.id.high_quota_direct_tab_outlet)
	TextView mTabOutlet;
	@BindView(R.id.high_quota_direct_viewpager)
	ViewPager mViewpager;
	@BindView(R.id.high_quota_direct_tab_online_line)
	View mTabOnlineLine;
	@BindView(R.id.high_quota_direct_tab_outlet_line)
	View mTabOutletLine;
	@BindView(R.id.no_network_layout)
	RelativeLayout mNoNetworkLayout;
	/**
	 * 预约门店按钮
	 */
	private Button mAppointBtn;
	/**
	 * 借款须知Dialog
	 */
	private CommonDialog mLoanNoticeDialog;

	private ViewPagerAdapter mPagerAdapter;

	private BankCardPresenter mBankCardPresenter;
	private ConfirmLoanPresenter mConfirmLoanPresenter;
	private LocationPresenter mLocationPresenter;
	private CustomerInfoPresenter mCustomerInfoPresenter;

	MyQuotaModel.ApplyStatus mApplyStatus;
	int mStatusCode;

	/**
	 * ViewPager里面的视图列表
	 */
	private List<View> mViewList = new ArrayList<>();
	private List<String> mTitles = new ArrayList<>();

	/**
	 * 定位信息
	 */
	private Location mLocation;
	/**
	 * 是否需要在定位成功之后自动预约门店
	 */
	private boolean mAutoCommit;
	/**
	 * 当前显示的tab
	 */
	private int mCurrentTab;

	public static BaseFragment newInstance(MyQuotaModel.ApplyStatus status, int savedTab) {
		BaseFragment fragment = new ComplexStatusFragment();
		Bundle args = new Bundle();
		args.putParcelable(ARG_APPLY_STATUS, status);
		args.putInt(ARG_SAVED_TAB, savedTab);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_BANK:
				mBankCardPresenter = (BankCardPresenter) data;
				mBankCardPresenter.attach(this);
				break;
			case LOADER_ID_CONFIRM_LOAN:
				mConfirmLoanPresenter = (ConfirmLoanPresenter) data;
				mConfirmLoanPresenter.attach(this);
				break;
			case LOADER_ID_LOCATE:
				mLocationPresenter = (LocationPresenter) data;
				mLocationPresenter.attach(this);
				PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				break;
			case LOADER_ID_CUSTOMER_INFO:
				mCustomerInfoPresenter = (CustomerInfoPresenter) data;
				mCustomerInfoPresenter.attach(this);
				break;
			default:
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_BANK:
				return new PresenterLoader<>(getActivity(), new BankCardPresenter.Generator());
			case LOADER_ID_CONFIRM_LOAN:
				return new PresenterLoader<>(getActivity(), new ConfirmLoanPresenter.Generator());
			case LOADER_ID_LOCATE:
				return new PresenterLoader<>(getActivity(), new LocationPresenter.Generator());
			case LOADER_ID_CUSTOMER_INFO:
				return new PresenterLoader<>(getActivity(), new CustomerInfoPresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(LOADER_ID_BANK, null, this);
		getLoaderManager().initLoader(LOADER_ID_CONFIRM_LOAN, null, this);
		getLoaderManager().initLoader(LOADER_ID_LOCATE, null, this);
		getLoaderManager().initLoader(LOADER_ID_CUSTOMER_INFO, null, this);
	}

	@Override
	public void onDetach() {
		dismissLoading();
		getLoaderManager().destroyLoader(LOADER_ID_BANK);
		getLoaderManager().destroyLoader(LOADER_ID_CONFIRM_LOAN);
		getLoaderManager().destroyLoader(LOADER_ID_LOCATE);
		getLoaderManager().destroyLoader(LOADER_ID_CUSTOMER_INFO);
		super.onDetach();
	}

	@Override
	public void onDestroyView() {
		dismissLoanNoticeDialog();
		super.onDestroyView();
		unbinder.unbind();
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_complex_status, container, false);
		unbinder = ButterKnife.bind(this, view);
		mApplyStatus = getArguments().getParcelable(ARG_APPLY_STATUS);
		mCurrentTab = getArguments().getInt(ARG_SAVED_TAB, 0);
		mStatusCode = MyQuotaPresenter.judgeComplexStatus(mApplyStatus);
		initView();
		initPage(view, mApplyStatus);
		return view;
	}

	private void initView() {
		mLayoutTitleBar.setBackgroundResource(0);
		mLayoutTitleBar.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_white));
		mTitleLeftIv.setImageResource(R.drawable.ic_help_black);
		mTitleRightIv.setImageResource(R.drawable.ic_message_black);
		MainController.initRedDot(mRedDotView);
	}

	private void initPage(View view, MyQuotaModel.ApplyStatus status) {
		mViewList.clear();
		mTitles.clear();
		mNoNetworkLayout.setVisibility(View.GONE);
		switch (mStatusCode) {
			//直批且额度大于20W，均未申请
			case Constants.COMPLEX_STATUS_DIRECT_HIGH_BOTH:
				initLoanPage();
				initOutletPage();
				initViewPager();
				initTitleTab(view);
				break;
			//直批且额度大于20W，线上已通过，线下已预约
			case Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_APPOINTED:
				initHasLoanPage();
				initOutletPage();
				initViewPager();
				initTitleTab(view);
				break;
			case Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_NONE://直批且额度大于20W，线上已通过，线下无额度
			case Constants.COMPLEX_STATUS_NOT_DIRECT_PASSED://非直批，借款申请已通过
			case Constants.COMPLEX_STATUS_DIRECT_LOW_PASSED://直批且额度小于20W，借款申请已通过
			case Constants.COMPLEX_STATUS_HAS_LOAN://已有存量借款
				initHasLoanPage();
				initViewPager();
				initTitleTab(view);
				break;
			case Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_ONLY://直批且额度大于20W，线上未申请，线下已预约
			case Constants.COMPLEX_STATUS_NOT_DIRECT://非直批，未预约
			case Constants.COMPLEX_STATUS_NOT_DIRECT_APPOINTED://非直批，已预约
				initOutletPage();
				initViewPager();
				initTitleTab(view);
				break;
			//直批且额度小于20W，未申请
			case Constants.COMPLEX_STATUS_DIRECT_LOW:
				initLoanPage();
				initViewPager();
				initTitleTab(view);
				break;
			default:
				// 未知状态，显示网络错误页面
				mTitles.add(getString(R.string.tab_lend));
				initTitleTab(view);
				mNoNetworkLayout.setVisibility(View.VISIBLE);
				mNoNetworkLayout.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						EventAgent.post(new QuotaEvent.RefreshStatusEvent(QuotaEvent.Event.QUOTA_REFRESH, null));
					}
				});
				break;
		}
	}

	/**
	 * 初始化线上借款界面
	 */
	private void initLoanPage() {
		View onlinePage = View.inflate(getContext(), R.layout.page_loan_online, null);
		switch (mStatusCode) {
			//直批且额度大于20W，均未申请
			case Constants.COMPLEX_STATUS_DIRECT_HIGH_BOTH:
				((TextView) onlinePage.findViewById(R.id.online_highest_quota)).setText(FormatUtils.getDecoratedAmount(Global.mMaxOnlineQuota));
				break;
			//直批且额度小于20W，未申请
			case Constants.COMPLEX_STATUS_DIRECT_LOW:
				setOnlineQuota(onlinePage);
				boolean canPromote = !TextUtils.isEmpty(mApplyStatus.promoteAmount) && Constants.PROMOTE_STATUS_HAVE.equals(mApplyStatus.promoteAmount);// && MyQuotaPresenter.lessThanMaxOnlineQuota(mApplyStatus);
				if (canPromote) {
					//可提额
					((TextView) onlinePage.findViewById(R.id.online_lending_hint)).setText(R.string.hint_increase_quota);
					onlinePage.findViewById(R.id.online_lending_hint).setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							//提额
							StatService.onEvent(getContext(), StatIDSet.EVENT_ID_INCREASE_LOAN_ENTRANCE);
							PreIncreaseLimitActivity.start(getActivity());
						}
					});
				} else {
					((TextView) onlinePage.findViewById(R.id.online_lending_hint)).setText(R.string.lending_online_hint);
				}
				/*boolean promoting = !TextUtils.isEmpty(mApplyStatus.promoteAmount) && Constants.PROMOTE_STATUS_ING.equals(mApplyStatus.promoteAmount);
				if(promoting){
					//提额申请中 需要显示提额loading界面
					EventAgent.post(new QuotaEvent.ShowIncreaseLoadingEvent());
				}*/
				break;
			default:
				break;
		}
		onlinePage.findViewById(R.id.lending_notice_tv).setOnClickListener(this);
		onlinePage.findViewById(R.id.online_loan_btn).setOnClickListener(this);
		((TelephoneTextView) onlinePage.findViewById(R.id.service_phone_tv)).setPageNo(Constants.PAGE_NO_MAIN_ACTIVITY);
		mViewList.add(onlinePage);
		mTitles.add(getString(R.string.loan_online));
	}

	private void setOnlineQuota(View view) {
		try {
			((TextView) view.findViewById(R.id.online_highest_quota)).setText(FormatUtils.getDecoratedAmount(mApplyStatus.quota.ts));
		} catch (NumberFormatException e) {
			((TextView) view.findViewById(R.id.online_highest_quota)).setText(FormatUtils.getDecoratedAmount(0));
		}
	}

	/**
	 * 初始化已有贷款界面
	 */
	private void initHasLoanPage() {
		StatService.onEvent(getContext(), StatIDSet.EVENT_ID_AUDIT_PASSED);
		View outletPage = View.inflate(getContext(), R.layout.page_has_loan, null);
		((TelephoneTextView) outletPage.findViewById(R.id.service_phone_tv)).setPageNo(Constants.PAGE_NO_MAIN_ACTIVITY);
		mViewList.add(outletPage);
		if (Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_APPOINTED == mStatusCode) {
			mTitles.add(getString(R.string.loan_online));
		} else {
			mTitles.add(getString(R.string.tab_lend));
		}
	}

	/**
	 * 初始化线下借钱界面
	 */
	private void initOutletPage() {
		View outletPage = View.inflate(getContext(), R.layout.page_loan_outlet, null);
		switch (mStatusCode) {
			//直批且额度大于20W，均未申请
			case Constants.COMPLEX_STATUS_DIRECT_HIGH_BOTH:
				setOutletQuota(outletPage);
				mAppointBtn = (Button) outletPage.findViewById(R.id.outlet_appoint_btn);
				setOutletBtnText(outletPage, R.string.appoint_outlet);
				break;
			//直批且额度大于20W，线上已通过，线下已预约
			case Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_APPOINTED:
				setOutletQuota(outletPage);
				showOutletAppointedHint(outletPage);
				Drawable noticeImage = getActivity().getResources().getDrawable(R.drawable.ic_notice_white);
				noticeImage.setBounds(0, 0, noticeImage.getMinimumWidth(), noticeImage.getMinimumHeight());
				((TextView) outletPage.findViewById(R.id.outlet_highest_quota_hint)).setCompoundDrawables(null, null, noticeImage, null);
				outletPage.findViewById(R.id.outlet_highest_quota_hint).setOnClickListener(this);
				setOutletCenterImg(outletPage, R.drawable.lending_outlet_search_center_bg);
				setOutletBtnText(outletPage, R.string.outlet_search);
				break;
			//直批且额度大于20W，线上未申请，线下已预约
			case Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_ONLY:
				setOutletQuota(outletPage);
				showOutletAppointedHint(outletPage);
				setOutletCenterImg(outletPage, R.drawable.lending_outlet_search_center_bg);
				setOutletBtnText(outletPage, R.string.outlet_search);
				break;
			//非直批，未预约
			case Constants.COMPLEX_STATUS_NOT_DIRECT:
				setOutletQuota(outletPage);
				boolean canPromote = !TextUtils.isEmpty(mApplyStatus.promoteAmount) && Constants.PROMOTE_STATUS_HAVE.equals(mApplyStatus.promoteAmount);
				if (canPromote) {
					//可提额
					((TextView) outletPage.findViewById(R.id.outlet_lending_hint)).setText(R.string.hint_increase_quota);
					outletPage.findViewById(R.id.outlet_lending_hint).setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							//提额
							StatService.onEvent(getContext(), StatIDSet.EVENT_ID_INCREASE_LOAN_ENTRANCE);
							PreIncreaseLimitActivity.start(getActivity());
						}
					});
				} else {
					((TextView) outletPage.findViewById(R.id.outlet_lending_hint)).setText(R.string.lending_outlet_hint);
				}
				mAppointBtn = (Button) outletPage.findViewById(R.id.outlet_appoint_btn);
				setOutletBtnText(outletPage, R.string.appoint_outlet);
				break;
			//非直批，已预约
			case Constants.COMPLEX_STATUS_NOT_DIRECT_APPOINTED:
				setOutletQuota(outletPage);
				showOutletAppointedHint(outletPage);
				setOutletCenterImg(outletPage, R.drawable.lending_outlet_search_center_bg);
				setOutletBtnText(outletPage, R.string.outlet_search);
				break;
			default:
				break;
		}
		outletPage.findViewById(R.id.lending_notice_tv).setOnClickListener(this);
		outletPage.findViewById(R.id.outlet_appoint_btn).setOnClickListener(this);
		((TelephoneTextView) outletPage.findViewById(R.id.service_phone_tv)).setPageNo(Constants.PAGE_NO_MAIN_ACTIVITY);

		mViewList.add(outletPage);
		mTitles.add(getString(R.string.loan_outlet));
	}

	private void setOutletBtnText(View view, int strId) {
		((Button) view.findViewById(R.id.outlet_appoint_btn)).setText(strId);
	}

	private void showOutletAppointedHint(View view) {
		view.findViewById(R.id.outlet_highest_quota_appointed_iv).setVisibility(View.VISIBLE);
	}

	private void setOutletCenterImg(View view, int imgId) {
		view.findViewById(R.id.outlet_center_iv).setBackgroundResource(imgId);
	}

	private void setOutletQuota(View view) {
		try {
			if (Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_APPOINTED == mStatusCode) {
				int quota = Integer.valueOf(mApplyStatus.quota.ts) - Global.mMaxOnlineQuota;
				((TextView) view.findViewById(R.id.outlet_highest_quota)).setText(FormatUtils.getDecoratedAmount(quota));
			} else {
				((TextView) view.findViewById(R.id.outlet_highest_quota)).setText(FormatUtils.getDecoratedAmount(mApplyStatus.quota.ts));
			}
		} catch (Exception e) {
			((TextView) view.findViewById(R.id.outlet_highest_quota)).setText(FormatUtils.getDecoratedAmount(0));
		}
	}

	private void initViewPager() {
		mPagerAdapter = new ViewPagerAdapter(mViewList, mTitles);
		mViewpager.setAdapter(mPagerAdapter);
		mViewpager.addOnPageChangeListener(mOnPageChangeListener);
	}

	private void initTitleTab(View view) {
		if (mTitles.size() == 1) {
			view.findViewById(R.id.high_quota_direct_tab).setVisibility(View.INVISIBLE);
			view.findViewById(R.id.high_quota_direct_tab_line).setVisibility(View.INVISIBLE);
			((TextView) view.findViewById(R.id.high_quota_direct_single_title)).setText(R.string.tab_lend);
			view.findViewById(R.id.high_quota_direct_single_title).setVisibility(View.VISIBLE);
			mCurrentTab = 0;
			postTabChangedEvent();
		} else if (mTitles.size() == 2) {
			view.findViewById(R.id.high_quota_direct_single_title).setVisibility(View.GONE);
			mTabOnline.setText(mTitles.get(0));
			mTabOutlet.setText(mTitles.get(1));
			view.findViewById(R.id.high_quota_direct_tab).setVisibility(View.VISIBLE);
			view.findViewById(R.id.high_quota_direct_tab_line).setVisibility(View.VISIBLE);
			if (mCurrentTab == 1) {
				mViewpager.setCurrentItem(mCurrentTab, true);
			}
			postTabChangedEvent();
		}
	}

	private void postTabChangedEvent() {
		EventAgent.post(new QuotaEvent.ComplexStatusTabChangedEvent(mCurrentTab));
	}

	private class ViewPagerAdapter extends PagerAdapter {
		private List<View> viewList;
		private List<String> titles;

		private ViewPagerAdapter(List<View> viewList, List<String> titles) {
			this.viewList = viewList;
			this.titles = titles;
		}

		@Override
		public int getCount() {
			return viewList.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(viewList.get(position));
			return viewList.get(position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return titles.get(position);
		}
	}

	private ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int position) {
			mCurrentTab = position;
			postTabChangedEvent();
			if (mTitles.size() == 2) {
				if (PAGE_ONLINE == position) {
					mTabOutletLine.setVisibility(View.INVISIBLE);
					mTabOnlineLine.setVisibility(View.VISIBLE);
					mTabOutlet.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_333333));
					mTabOnline.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_4b7cf9));
				} else if (PAGE_OUTLET == position) {
					mTabOnlineLine.setVisibility(View.INVISIBLE);
					mTabOutletLine.setVisibility(View.VISIBLE);
					mTabOutlet.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_4b7cf9));
					mTabOnline.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_333333));
				}
			}
		}

		@Override
		public void onPageScrollStateChanged(int state) {
		}
	};

	@OnClick({R.id.title_left_iv, R.id.title_right_iv, R.id.high_quota_direct_tab_online, R.id.high_quota_direct_tab_outlet,
			R.id.high_quota_direct_tab_outlet_line, R.id.high_quota_direct_tab_online_line})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.title_left_iv:
				EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_HELP_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
				break;
			case R.id.title_right_iv:
				MainController.hideRedDot(mRedDotView);
				EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_MESSAGE_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
				break;
			case R.id.high_quota_direct_tab_online:
			case R.id.high_quota_direct_tab_online_line:
				if (PAGE_ONLINE != mViewpager.getCurrentItem()) {
					mViewpager.setCurrentItem(PAGE_ONLINE, true);
				}
				break;
			case R.id.high_quota_direct_tab_outlet:
			case R.id.high_quota_direct_tab_outlet_line:
				if (PAGE_OUTLET != mViewpager.getCurrentItem()) {
					mViewpager.setCurrentItem(PAGE_OUTLET, true);
				}
				break;
			default:
				break;
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onRedDotShowEvent(QuotaEvent.ShowRedDotEvent event) {
		mRedDotView.setVisibility(View.VISIBLE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.lending_notice_tv:
				if (Constants.COMPLEX_STATUS_DIRECT_HIGH_BOTH == mStatusCode) {
					HashMap<String, String> map = new HashMap<>();
					map.put(StatService.ATTRIBUTE_KEY_ONE, mApplyStatus.amountState);
					map.put(StatService.ATTRIBUTE_KEY_TWO, mApplyStatus.loanState);
					map.put(StatService.ATTRIBUTE_KEY_THREE, mApplyStatus.promoteAmount);
					StatService.onEvent(getContext(), StatIDSet.EVENT_ID_CHECK_BORROWING_REQUIREMENTS, map);
					showLoanNoticeDialog();
				} else {
					EventAgent.post(new QuotaEvent.ShowLoanNoticeEvent(QuotaEvent.ShowLoanNoticeEvent.QUOTA_SHOW_LOAN_NOTICE, Constants.PAGE_NO_MAIN_ACTIVITY));
				}
				break;
			case R.id.online_loan_btn:
				// 立即借钱
				showLoading(false);
				mBankCardPresenter.getMyBankCard(true);
				break;
			case R.id.outlet_appoint_btn:
				// 根据不同状态处理
				String btnString = ((Button) v).getText().toString();
				if (getString(R.string.outlet_search).equals(btnString)) {
					//查询门店
					OutletActivity.start(getActivity());
				} else if (getString(R.string.appoint_outlet).equals(btnString)) {
					StatService.onEventWithSingleAttribute(getContext(), StatIDSet.EVENT_ID_APPOINT_OUTLET, mApplyStatus.isDirectApproval);
					// 预约门店
					if (Constants.COMPLEX_STATUS_DIRECT_HIGH_BOTH == mStatusCode) {
						//放弃线上，直接线下
						showTwoBtnDialog(R.string.give_up_online_quota_alert, R.string.cancel, R.string.go_on, new CommonDialog.ButtonClickListener() {
							@Override
							public void onCancel(CommonDialog dialog) {
								StatService.onEvent(getContext(), StatIDSet.EVENT_ID_APPOINT_OUTLET_CONFIRM);
								dialog.dismiss();
								appointOutlet();
							}

							@Override
							public void onConfirm(CommonDialog dialog) {
								StatService.onEvent(getContext(), StatIDSet.EVENT_ID_APPOINT_OUTLET_CANCEL);
								dialog.dismiss();
							}
						}, true);
					} else {
						appointOutlet();
					}
				}
				break;
			case R.id.outlet_highest_quota_hint:
				if (Constants.COMPLEX_STATUS_DIRECT_HIGH_OUTLET_APPOINTED == mStatusCode) {
					showOneBtnDialog(R.string.outlet_quota_adjustment_remind, R.string.got_it);
				}
				break;
			default:
				break;
		}
	}

	/**
	 * 预约门店
	 */
	private void appointOutlet() {
		mAppointBtn.setEnabled(false);
		if (null == mLocation) {
			mAutoCommit = true;
			PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
		} else {
			mAutoCommit = false;
			showLoading(false);
			confirmLoan();
		}
	}

	/**
	 * 线下借款提交
	 */
	private void confirmLoan() {
		mConfirmLoanPresenter.confirmLoan("36", mApplyStatus.quota.ts, String.valueOf(mLocation.longitude), String.valueOf(mLocation.latitude), Constants.LOAN_OUTLET);
	}

	@Override
	public void bindCardSuccess() {
	}

	@Override
	public void bindCardFailed(String msg) {
	}

	@Override
	public void hasBindBankCard(boolean isManual, List<BoundBankCards.BankInfo> bankInfo) {
		HashMap<String, String> map = new HashMap<>();
		map.put(StatService.ATTRIBUTE_KEY_ONE, StatService.ATTRIBUTE_VALUE_ONE);
		if (MyQuotaPresenter.largeThanMaxOnlineQuota(mApplyStatus)) {
			map.put(StatService.ATTRIBUTE_KEY_TWO, StatService.ATTRIBUTE_VALUE_ONE);
		} else {
			map.put(StatService.ATTRIBUTE_KEY_TWO, StatService.ATTRIBUTE_VALUE_TWO);
		}
		StatService.onEvent(getContext(), StatIDSet.EVENT_ID_BEGIN_BORROW_MONEY, map);
		ProcessActivity.start(getActivity(), mApplyStatus, bankInfo);
	}

	@Override
	public void neverBindBankCard(boolean isManual) {
		HashMap<String, String> map = new HashMap<>();
		map.put(StatService.ATTRIBUTE_KEY_ONE, StatService.ATTRIBUTE_VALUE_TWO);
		if (MyQuotaPresenter.largeThanMaxOnlineQuota(mApplyStatus)) {
			map.put(StatService.ATTRIBUTE_KEY_TWO, StatService.ATTRIBUTE_VALUE_ONE);
		} else {
			map.put(StatService.ATTRIBUTE_KEY_TWO, StatService.ATTRIBUTE_VALUE_TWO);
		}
		StatService.onEvent(getContext(), StatIDSet.EVENT_ID_BEGIN_BORROW_MONEY, map);
		mCustomerInfoPresenter.getCustomerInfo(Constants.CUSTOMER_TYPE_IDENTITY);
	}

	@Override
	public void customerInfoExist(String type, CustomerBean customerBean) {
		if(Constants.CUSTOMER_TYPE_IDENTITY.equals(type)){
			Global.LOGIN_REAL_NAME = customerBean.identity.iname;
			BankCardActivity.start(getActivity(), null, mApplyStatus, Constants.KEY_GOTO_BIND_CARD_FROM_HAVE_QUOTA_FRAGMENT);
		}
	}

	@Override
	public void customerInfoNotExist(String type, String msg) {
		if(Constants.CUSTOMER_TYPE_IDENTITY.equals(type)){
			showOneBtnDialog(getString(R.string.should_real_name_before_bind_card), getString(R.string.got_it));
		}
	}

	@Override
	public void getCustomerInfoError(String type, String msg) {
		if(Constants.CUSTOMER_TYPE_IDENTITY.equals(type)) {
			showToast(msg);
		}
	}

	@Override
	public void requestBindBankCardFailed(boolean isManual) {
	}

	@Override
	public void getSupportBankSuccess(List<BankCardModel.SupportBankList.SupportBank> supportBankList) {
	}

	@Override
	public void getSupportBankFailed(String msg) {
	}

	@Override
	public void bindCardRetCode(String retCode) {

	}

	@Override
	public void onFunctionalCompleted(boolean autoTips) {
		super.onFunctionalCompleted(autoTips);
		dismissLoading();
	}

	@Override
	public void confirmLoanSuccess(ConfirmLoanModel.ConfirmLoan confirmLoan) {
		mAppointBtn.setEnabled(true);
		OutletActivity.start(getActivity());
	}

	@Override
	public void confirmLoanFailure(String tips) {
		showToast(tips);
		mAppointBtn.setEnabled(true);
	}

	@Override
	public void confirmLoanRepeat(String tips) {
		showToast(tips);
		EventAgent.post(new QuotaEvent.RefreshStatusEvent(QuotaEvent.Event.QUOTA_REFRESH, null));
	}

	@Override
	public void creditReportingOutdated() {
		showToast(R.string.credit_report_outdated);
		// 征信过期 重新获取额度状态
		EventAgent.post(new QuotaEvent.RefreshStatusEvent(QuotaEvent.Event.QUOTA_REFRESH, null));
	}

	@Override
	public void getIdCardSuccess(IdCardModel.IdCard idCard) {

	}

	@Override
	public void getIdCardFailure(String s) {

	}

	@Override
	public void onLocateSuccess(Location location) {
		mLocation = location;
		if (mAutoCommit)
			confirmLoan();
	}

	@Override
	public void onLocateFail(boolean noPermission) {
		if (mAutoCommit) {
			dismissLoading();
			mAutoCommit = false;
			showToast(R.string.locate_need_retry);
			mAppointBtn.setEnabled(true);
		}
	}

	@Override
	public void showDialog() {

	}

	@Override
	public void dismissDialog() {

	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.ACCESS_COARSE_LOCATION:
					if (permission.granted) {
						if (mAutoCommit) {
							showLoading(false);
						}
						mLocationPresenter.startLocation(false);
					} else {
						if (mAutoCommit) {
							dismissLoading();
						}
						showNeedPermission(getString(R.string.location_right_hint, getString(R.string.app_name)));
					}
					break;
				default:
					break;
			}

		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};

	private void showNeedPermission(String msg) {
		showOneBtnDialog(msg, getString(R.string.got_it));
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		switch (functionalCode) {
			case ConfirmLoanModel.METHOD_CONFIRM_LOAN:
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						showToast(R.string.network_need_retry);
						mAppointBtn.setEnabled(true);
					}
				});
				break;
		}
	}

	private void showLoanNoticeDialog() {
		if (null == mLoanNoticeDialog)
			mLoanNoticeDialog = new CommonDialog(getActivity(), getString(R.string.lending_notice), true, R.layout.dialog_lending_notice_complex);
		mLoanNoticeDialog.show();
	}

	private void dismissLoanNoticeDialog() {
		if (mLoanNoticeDialog != null && mLoanNoticeDialog.isShowing()) {
			mLoanNoticeDialog.dismiss();
			mLoanNoticeDialog = null;
		}
	}
}

